import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jicaimao_flutter/entity/loginbean.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/event/login_event.dart';
import 'package:jicaimao_flutter/utils/event_bus.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/sp_key.dart';
import 'package:jicaimao_flutter/utils/string_utils.dart';
import 'package:jicaimao_flutter/utils/sp_utils.dart';
import 'package:jicaimao_flutter/views/mine/forget_password_page.dart';
import 'package:jicaimao_flutter/views/mine/quick_login_page.dart';
import 'package:jicaimao_flutter/views/mine/register_page.dart';
import 'package:jicaimao_flutter/widget/app_bar.dart';


/// 登录页面

class LoginPage extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<LoginPage> {
  final phone_controller = TextEditingController();

  final password_controller = TextEditingController();
  bool psw_noshow = true;
  bool isClearshow = false;
  bool isGologin = false;
  EventBus eventBus = new EventBus();
  StreamSubscription listen;
  _LoginState(){
     listen = eventBus.on<LoginEvent>().listen((event) {
       // All events are of type UserLoggedInEvent (or subtypes of it).
       if(event.loginComplete==1){
         Navigator.pop(context);
       }
     });
  }
  @override
  void dispose() {
    listen?.cancel();
    super.dispose();
  }

  _login() {
    String phone_str = phone_controller.text;
    String psw_str = password_controller.text;
    if (phone_str.isEmpty) {
      showToast("请输入手机号码");
      return;
    }
    if (!RegexUtil.isMobileExact(phone_str)) {
      showToast("手机号格式不正确");
      return;
    }
    if (psw_str.isEmpty) {
      showToast("请输入密码");
      return;
    }
    _loadDataLogin(phone_str, psw_str);
  }

  void _loadDataLogin(String phone, String psw) async {
    String url = NetAddress.login;
//    print("key=${userId}");
    var data = {'terminal': 1, "mobile": phone, "password": psw};
    var respone = await HttpUtil().post(url, data: data);

    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    if (loginBean.code == "200") {
//      print(loginBean.result.userId);
      showToast( loginBean.msg);
      SpUtils.putString(SpKey.KEY_USER_ID, loginBean.result.userId);
      eventBus.fire(LoginEvent(1));
    } else {
      showToast(loginBean.msg);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
//    phone_controller.addListener(() {
//      print("输入${phone_controller.text}");
//    });
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarNormal("登录"),
      body: new SingleChildScrollView(
        child: new ConstrainedBox(
          constraints: new BoxConstraints(
            minHeight: 120.0,
          ),
          child: Container(
            margin: EdgeInsets.fromLTRB(20, 0, 20, 0),
            child: Column(
              children: <Widget>[
                //logo
                Container(
                  margin: EdgeInsets.only(top: 40),
                  height: 70,
                  child: Center(
                    child: Image.asset(
                      'images/icon.png',
                      width: 70,
                      height: 70,
                    ),
                  ),
                ),
                ///输入框
                _inputPhone(),
                Container(
                  height: 1,
                  color: Color(0xffDCDCDC),
                ),
                _inputPassword(),
                GestureDetector(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ForgetPasswordPage("2")),
                    );
                  },
                  child: Container(
                      alignment: Alignment.centerRight,
                      padding: EdgeInsets.only(top: 10, bottom: 10),
                      child: Text(
                        "忘记密码",
                        style: TextStyle(color: Color(0xffad5afe)),
                      )),
                ),

                GestureDetector(
                  onTap: _login,
                  child: Container(
                      margin: EdgeInsets.only(top: 40),
                      decoration: new BoxDecoration(
                          color:
                              isGologin ? Color(0xffad5afe) : Color(0xffD4d4d4),
                          borderRadius: BorderRadius.circular(3.0)),
                      alignment: Alignment.center,
                      height: 40,
                      width: double.infinity,
                      child: Text(
                        "登录",
                        style: TextStyle(color: Colors.white),
                      )),
                ),
                Container(
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          ///注册
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => RegisterPage()),///RegisterConfirmPage(mobile: "13688861688",verificationCode: "1232",)),
                          );
                        },
                        child: Container(
                          padding: EdgeInsets.only(top: 10, bottom: 10),
                          child: Text(
                            "注册新账号",
                            style: TextStyle(fontSize: 14),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          ///快速登录
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => QuickLoginPage()),
                          );
                        },
                        child: Container(
                          padding: EdgeInsets.only(top: 10, bottom: 10),
                          child: Text("快捷登录", style: TextStyle(fontSize: 14)),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  _inputPhone() {
    return Container(
        height: 40,
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        margin: EdgeInsets.fromLTRB(0, 40, 0, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                onChanged: (text) {
                  String pNum = phone_controller.text;
                  String pPassWord = password_controller.text;
                  bool loginEnd = false;
                  if (pPassWord.isNotEmpty &&
                      pNum.isNotEmpty &&
                      RegexUtil.isMobileExact(pNum) &&
                      StringUtils.checkAccountMarkNmu(pPassWord)) {
                    loginEnd = true;
                  } else {
                    loginEnd = false;
                  }

                    setState(() {
                      isClearshow = text.length > 0;
                      if (loginEnd) {
                        isGologin = true;
                      } else {
                        isGologin = false;
                      }
                    });
                },
                controller: phone_controller,
                inputFormatters: [LengthLimitingTextInputFormatter(11)],
                maxLength: 11,
                maxLines: 1,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    counterText: '',
                    border: InputBorder.none,
                    hintText: '请输入手机号',
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                width: 40,
                height: 40,
                padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
                child: Image.asset(isClearshow ? 'images/icon_error.png' : ''),
              ),
              onTap: () {
                phone_controller.clear();
                setState(() {
                  isClearshow = !isClearshow;
                });
              },
            )
          ],
        ));
  }

  _inputPassword() {
    return Container(
        height: 40,
        padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                controller: password_controller,
                keyboardType: TextInputType.text,
                onChanged: (text) {
                  String pNum = phone_controller.text;
                  String pPassWord = password_controller.text;
                  bool loginEnd = false;
                  if (pPassWord.isNotEmpty &&
                      pNum.isNotEmpty &&
                      RegexUtil.isMobileExact(pNum) &&
                      StringUtils.checkAccountMarkNmu(pPassWord)) {
                    loginEnd = true;
                  } else {
                    loginEnd = false;
                  }
                  setState(() {
                    if (loginEnd) {
                      isGologin = true;
                    } else {
                      isGologin = false;
                    }
                  });
                },
                maxLines: 1,
                obscureText: psw_noshow,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    border: InputBorder.none,
                    hintText: '请输入密码',
                    counterText: '',
                    ///限制最大长度后
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                  width: 40,
                  height: 40,
                  padding: EdgeInsets.all(10),
                  child: Image.asset(psw_noshow
                      ? 'images/ps_notsee.png'
                      : 'images/ps_see.png')),
              onTap: () {
                setState(() {
                  psw_noshow = !psw_noshow;
                });
              },
            )
          ],
        ));
  }


  void showToast(String tipMsg) {
    Fluttertoast.showToast(
        msg: tipMsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.black87,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
